package com.example.teacher.servlets;


import com.example.teacher.model.Teacher;
import com.example.teacher.utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = "/teachers",loadOnStartup = 1)
public class GetTeacherServlet extends HttpServlet {
    Connection connection=null;
    PreparedStatement statement=null;
    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            connection=DBUtil.getConnection();
            String sql="select * from t_teacher";
            statement= connection.prepareStatement(sql);
            ResultSet resultSet=statement.executeQuery();
            List<Teacher> teacherList=new ArrayList<>();
            while (resultSet.next()){
                int id=resultSet.getInt("id");
                String name=resultSet.getString("name");
                Teacher teacher=new Teacher(id,name);
                teacherList.add(teacher);
            }
            req.getServletContext().setAttribute("teacherList",teacherList);
            resp.sendRedirect("teacher.jsp");

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (connection!=null){
                    connection.close();
                }
                if (statement!=null){
                    statement.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
